package edu.hznu.retroSnakerPlanServer.utils;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * create by Cliven on 2018-05-31 16:48
 */
public class ByteUtils {

    final private static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();

    /**
     * 字节数组转字节
     *
     * @param bytes 数组
     * @return 字节
     * @author from stackoverflow
     * @since 2018-06-03 16:21:44
     */
    public static String bytesToHex(Byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            if (i % 4 == 0) {
                sb.append("\n");
            }
            sb.append(String.format("%02X ", bytes[i]));
        }
        return sb.toString();
    }

    public static String bytesToHex(byte[] bytes, int offset, int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            if (i % 4 == 0) {
                sb.append("\n");
            }
            sb.append(String.format("%02X ", bytes[offset + i]));
        }
        return sb.toString();
    }


    public static Integer integer(byte b) {
        return (b & 0xFF);
    }

    /**
     * byte数组转为短整形
     *
     * @param bytes 字节数组
     * @param off   偏移位置
     * @return 整形
     * @author Cliven
     * @since 2018-05-31 16:50:15
     */
    public static Integer byteToShortInteger(Byte[] bytes, int off) {
        int high = bytes[off + 1];
        int low = bytes[off];
        return (high << 8 & 0xFF00) | (low & 0xFF);
    }

    /**
     * byte数组转为整形
     *
     * @param bytes 数组
     * @return
     */
    public static Integer byteToInt(Byte[] bytes, int off) {
        return bytes[off] & 0xFF |
                (bytes[off + 1] & 0xFF) << 8 |
                (bytes[off + 2] & 0xFF) << 16 |
                (bytes[off + 3] & 0xFF) << 24;
    }
}
